import 'dart:convert';
import 'dart:io';

import 'package:azlistview/azlistview.dart';
import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/common_widget.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/im/model/groupmodel.dart';
import 'package:find_friend/pages/im/pages/conversation_page.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:path_provider/path_provider.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';

class MsgFriendPage extends StatefulWidget {
  
  final bool issendImage;
  final String imgUrl;

  const MsgFriendPage({Key key, this.issendImage = false, this.imgUrl}) : super(key: key);

  @override
  _MsgFriendPageState createState() => _MsgFriendPageState();
}

class _MsgFriendPageState extends State<MsgFriendPage> {

  List<FriendModel> list = [];

    String _suspensionTag = "";

  @override
  void initState() {
    super.initState();
  
    _requestData();
  }

  _requestData() {
    Networktool.request(API.friend, params: {"all": 1}, method: NETWORKHTTPMethod.GET, success: (data){
      if(data != null) {
        data['data'].forEach((v) {
          list.add(FriendModel.fromJson(v));
        });
      }
      _handleList(list);
      _suspensionTag = list.first.getSuspensionTag();
      if(mounted) setState(() { });
    });
  }

  void _handleList(List<FriendModel> list) {
    if (list == null || list.isEmpty) return;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin =
          PinyinHelper.getPinyinE(list[i].username);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;
      if (RegExp("[A-Z]").hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = "#";
      }
    }
    //根据A-Z排序
    SuspensionUtil.sortListBySuspensionTag(list);
  }

  Widget _buildSusWidget(String susTag) {
    susTag = (susTag == "★" ? "特别关注" : susTag);
    return Container(
      padding: const EdgeInsets.only(left: 10.0, bottom: 10,),
      alignment: Alignment.centerLeft,
      color: Colors.white,
      child: Text(
        '$susTag',
        textAlign: TextAlign.left,
        style: instanceTextStyle(11, APP_font_deep_grey),
      ),
    );
  }

  //  用户cell
  Widget _buildListItem(FriendModel model) {
    String susTag = model.getSuspensionTag();
    susTag = (susTag == "★" ? "特别关注" : susTag);
    return Column(
      children: <Widget>[
        Offstage(
          offstage: model.isShowSuspension != true,
          child: _buildSusWidget(susTag),
        ),
        InkWell(
          onTap: (){
            if(widget.issendImage){
              _sendImgageAndDownload(model);
              return;
            }
            Map arg = {"targetId":model.mobile, "nickname":model.remarkname,};
            // Navigator.of(context).push(CupertinoPageRoute(builder: (context) => ));
            push(context, ConversationPage(
              arguments: arg,
              onModRemarkName: (name){
                setState(() {
                  model.followRemark = name;
                });
              },
            ));
          },
          child: Container(
            margin: const EdgeInsets.only(bottom: 10, right: 5, left: 15),
            child: Row(
              children: [
                CustomCircleAvatar(size: 46.h,url: model.avatar,),
                SizedBox(width: 5,),
                Text(model.remarkname ?? "--", style: instanceTextStyle(14, APP_font_black),)
              ],
            ),
          ),
        )
      ],
    );
  }

  void _sendImgageAndDownload(FriendModel model) async {
    
    getApplicationDocumentsDirectory().then((value) async {
      String localpath = value.path + "AnyImg" + widget.imgUrl.split("/").last;
      print(localpath);
      var file = File(localpath);
      bool isexists = await file.exists();
      if(isexists) {
        print("本地");
        _sendImageWithPath(file.path, model);
      } else {
        print("下载");
        AlertTool.showLoadingDialog(context);
        Networktool.downloadImage(widget.imgUrl, success: (data) {
          Navigator.of(context).pop();
          file.writeAsBytes(data).then((value) => _sendImageWithPath(value.path, model));
        });
      }
    });
  }

  void _sendImageWithPath(String path, FriendModel model) async {
    ImageMessage imgMsg = ImageMessage.obtain(path);
    imgMsg.sendUserInfo = await _getCurrentUserInfo(model);
    RongcloudImPlugin.sendMessage(RCConversationType.Private, model.mobile, imgMsg).then((value) => AlertTool.showToast("发送成功"));
  }

  Future<UserInfo> _getCurrentUserInfo(FriendModel model) async {
    SharedUserInfo user = await SharedUserInfo.instance();
    final u = UserInfo();
    u.name = user.nickname;
    u.portraitUri = user.avatar;
    u.userId = user.mobile;
    u.extra = json.encode({"id":model.mobile, "name": model.followRemark, "portrait":model.avatar}); // 对方的信息
    return u;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: widget.issendImage == true ? AppBar(
        title: Text("选择好友"),
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          onPressed: (){
            Navigator.of(context).pop();
          },
          icon: Image.asset("assets/fanhui.png"),
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(colors: [
              const Color(0xFFffe92e),
              const Color(0xFFfbd001),
            ], begin: Alignment(-1.5,0.5), end: Alignment(0, 0)),
          ),
        ),
      ) : null,
      body: Container(
        color: Colors.white,
        child: AzListView(
          data: list,
          itemBuilder: (context, model) => _buildListItem(model),
          suspensionWidget: _buildSusWidget(_suspensionTag),
          isUseRealIndex: false,
          itemHeight: 46.h.toInt(),
          showIndexHint: false,
          indexBarBuilder: (context, tags, onTouch){
            return Container(
              margin: const EdgeInsets.only(bottom: 50),
              child: IndexBar(
                data: tags,
                textStyle: instanceTextStyle(11, APP_font_deep_grey),
                width: 36,
                itemHeight: 14.h.toInt(),
                touchDownTextStyle: instanceTextStyle(11, APP_font_deep_grey),
                onTouch: onTouch,
              ),
            );
          },
          onSusTagChanged: (tag){
            setState(() {
              _suspensionTag = tag;
            });
          },
        ),
      ),
    );
  }
}